class ScrollTop {
  constructor(options) {
    this.$options = Object.assign(
      {
        bottom: 100,
        content: "TOP",
      },
      options
    );

    // 按钮元素
    this.$el = this.createElement();

    this.addDocumentScrollEvent();

    this.addButtonEvent();
  }

  //在页面中添加按钮元素
  createElement() {
    const div = document.createElement("div");
    div.classList.add("scrollTop");
    div.innerHTML = this.$options.content;
    document.body.appendChild(div);
    return div;
  }

  //添加事件
  addDocumentScrollEvent() {
    document.addEventListener("scroll", () => {
      //console.log(document.documentElement.scrollTop);
      let { scrollTop, clientHeight, offsetHeight } = document.documentElement;
      console.log(scrollTop, clientHeight, offsetHeight);
      const status =
        scrollTop + clientHeight > offsetHeight - this.$options.bottom;
      this.$el.classList[status ? "add" : "remove"]("show");
    });
  }

  //doc.houdunren.com
  addButtonEvent() {
    this.$el.addEventListener("click", () => {
      //document.documentElement.scrollTop = 0;
      document.documentElement.scrollIntoView({
        block: "start",
        behavior: "smooth",
      });
    });
  }
}

export default (config) => {
  return new ScrollTop(config);
};
